﻿using Microsoft.AspNetCore.Components.Authorization;
using System.Net.Http.Headers;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Masa.Blazor;
using Blazored.LocalStorage;

namespace Bookify.Web.Services.Auth
{
    public class AuthProvider : AuthenticationStateProvider
    {
        //private ClaimsPrincipal _currentUser = new ClaimsPrincipal(new ClaimsIdentity());
        private readonly ILocalStorageService _localStorage;
        private readonly JwtSecurityTokenHandler _jwtSecurityTokenHandler;

        public string JwtToken { set; get; }


        public AuthProvider()
        {
            _jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
        }

        public override async Task<AuthenticationState> GetAuthenticationStateAsync()
        {
            var user = new ClaimsPrincipal(new ClaimsIdentity());            
            if (JwtToken.IsNullOrWhiteSpace())
            {
                return new AuthenticationState(user);
            }

            var saveToken = JwtToken;
            var tokenContent = _jwtSecurityTokenHandler.ReadJwtToken(saveToken);
            // Token是否超时           
            if (tokenContent.ValidTo.ToLocalTime() < DateTime.Now)
            {
                JwtToken = string.Empty;
                await _localStorage.RemoveItemAsync("token");
                return new AuthenticationState(user);
            }

            var claims = GetClaimsAsync();
            user = new ClaimsPrincipal(new ClaimsIdentity(claims));
            return new AuthenticationState(user);

            //var claimsIdentity = new ClaimsIdentity("Custome");

            //claimsIdentity.AddClaim(new(ClaimTypes.Name, "admin"));
            //claimsIdentity.AddClaim(new(ClaimTypes.Email, "test@test.com"));

            //ClaimsPrincipal _currentUser = new ClaimsPrincipal(claimsIdentity);

            //var authState = Task.FromResult(new AuthenticationState(_currentUser));
            ////NotifyAuthenticationStateChanged(authState);
            //return new AuthenticationState(_currentUser);
        }

        private List<Claim> GetClaimsAsync()
        {
            var savedToken = JwtToken;
            var tokenContent = _jwtSecurityTokenHandler.ReadJwtToken(savedToken);
            var claims = tokenContent.Claims.ToList();
            claims.Add(new Claim(ClaimTypes.Name, tokenContent.Subject));
            return claims;
        }

        /// <summary>
        /// 登入
        /// </summary>
        /// <returns></returns>
        public void LoggedIn()
        {
            var claims = GetClaimsAsync();
            var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt"));
            var authStatus = Task.FromResult(new AuthenticationState(user));
            NotifyAuthenticationStateChanged(authStatus);
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        public void Logout()
        {
            JwtToken = string.Empty;
            var nobody = new ClaimsPrincipal(new ClaimsIdentity());
            var authStatus = Task.FromResult(new AuthenticationState(nobody));
            NotifyAuthenticationStateChanged(authStatus);
        }
    }
}
